import {Component, OnInit, AfterViewInit, OnDestroy, ElementRef} from '@angular/core';
import {RxjsService} from './rxjs.service';
import {HttpService} from '@kylin/http';
import {fromEvent, interval} from 'rxjs';
import {map} from 'rxjs/operators';


@Component({
    selector: 'kylin-rxjs',
    templateUrl: './rxjs.component.html',
    styleUrls: ['./rxjs.component.less']
})
export class RxjsComponent implements OnInit, AfterViewInit, OnDestroy {

    clickEvent: any;
    buttonEvent: any;

    constructor(private rxjsService: RxjsService,
                private http: HttpService,
                private elementRef: ElementRef
    ) {
    }

    timerInit() {
        const button = this.elementRef.nativeElement.querySelector('button');
        const click$ = fromEvent(button, 'click');
        const interval$ = interval(1000);
        const clicksToInterval$ = click$.pipe(map(event => {
            return interval$;
        }));
        clicksToInterval$.subscribe(intervalObservable => {
            this.buttonEvent = intervalObservable.subscribe(num => {
                console.log(num);
            })
        });
    }


    ngOnInit() {
        const source$ = fromEvent(document, 'click');
        const example$ = source$.pipe(map(event => console.log(event)));
        this.clickEvent = example$.subscribe(val => console.log(val));
    }

    ngAfterViewInit() {
        this.timerInit();
        const foo = {name: 'ma', age: 20, location: 'xian'};
        console.log(Object.entries(foo));
    }

    ngOnDestroy() {
        if (this.buttonEvent) {
            this.buttonEvent.unsubscribe();
        }

        if (this.clickEvent) {
            this.clickEvent.unsubscribe();
        }
    }
}
